package com.dobbyspringside.modules.nosql.redis.pool;

import org.apache.commons.pool2.impl.GenericObjectPool;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.util.Pool;

/**
 * jedis连接池
 * Created by liguoqing on 2016/3/1.
 */
public abstract class JedisPool extends Pool<Jedis> {

    protected String poolName;

    protected HostAndPort address;

    protected ConnectionInfo connectionInfo;


    /**
     * 创建一个连接池配置
     * @param maxPoolSize
     * @return
     */
    public static JedisPoolConfig createPoolConfig(int maxPoolSize) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxPoolSize);
        config.setMaxIdle(maxPoolSize);
        config.setTimeBetweenEvictionRunsMillis(600 * 1000);

        return config;
    }


    /**
     * 使用连接信息和连接池配置来初始化一个内部的连接池
     */
    protected void initInternalPool(HostAndPort address,ConnectionInfo connectionInfo,JedisPoolConfig config) {
        this.address = address;
        this.connectionInfo = connectionInfo;
        JedisFactory jedisFactory = new JedisFactory(address.getHost(),address.getPort(),connectionInfo.getTimeout(),
                connectionInfo.getPassword(),connectionInfo.getDatabase());

        internalPool = new GenericObjectPool<Jedis>(jedisFactory, config);
    }


    public HostAndPort getAddress() {
        return address;
    }

    public ConnectionInfo getConnectionInfo() {
        return connectionInfo;
    }

    @Override
    public void returnResource(final Jedis resource) {
        if(null != resource) {
            resource.resetState();
            returnBrokenResourceObject(resource);
        }
    }

    @Override
    public void returnBrokenResource(final Jedis resource) {
        if(null != resource) {
            returnBrokenResourceObject(resource);
        }
    }
}
